package net.blogways.ordermgr.common.command;

import com.asiainfo.bpc.service.SqlCodeService;
import com.asiainfo.bpc.utils.ToolFactory;
import net.blogways.ordermgr.common.service.CodeToNameService;
import net.blogways.ordermgr.util.RescodeConstants;
import com.asiainfo.utils.Utils;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;

import org.apache.commons.chain.Command;
import org.apache.commons.chain.Context;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * @author wanghui
 *         Created on 2017/11/1.
 */
@Component("common:common")
public class CommonCommand implements Command{

  private final Logger logger = LoggerFactory.getLogger(getClass());

  @Override
  public boolean execute(Context context) throws Exception {
    return false;
  }

  public boolean getDatabaseTime(Context context) throws ExecutionException {
    SqlCodeService service = ToolFactory.getInstance().getSqlCodeService();
    List l = service.select("NOW", "COMMON", new HashMap<>());
    context.put(
        "now",
        DateFormatUtils
            .format(
                (Date) ((Map) l.get(0)).get("now"),
                "yyyy-MM-dd hh:mm:ss"
            )
    );
    return Utils.returnOk(context, "common_ok");
  }

  public boolean codeToName(Context context) throws Exception {
    String resultName;
    CodeToNameService codeToNameService = (CodeToNameService) ToolFactory
        .getInstance()
        .getContext()
        .getBean("codeToNameService");
    try {
      resultName = codeToNameService.code2Name(
          context.get("tableName").toString(),
          context.get("code").toString(),
          context.get("typeName").toString(),
          context.containsKey("locale") ? context.get("locale").toString(): ""
      );
    } catch (Exception e) {
      e.printStackTrace();
      return Utils.returnFalseResult(context, RescodeConstants.SELECT_FAIL, "查询失败");
    }
    context.put("resultName", resultName);
    return Utils.returnOk(context, "select_ok");
  }
}
